package com.jfirer.mvc.viewrender.impl;

import com.jfirer.dson.Dson;
import com.jfirer.jfire.core.inject.notated.PropertyRead;
import com.jfirer.mvc.viewrender.DefaultResultType;
import com.jfirer.mvc.viewrender.ViewRender;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.Charset;

@Resource
public class JsonRender implements ViewRender
{
	@PropertyRead("encode")
	private String	encode	= "UTF-8";
	private Charset	charset;
	
	@PostConstruct
	public void init()
	{
		charset = Charset.forName(encode);
	}
	
	@Override
	public void render(HttpServletRequest request, HttpServletResponse response, Object result) throws Throwable
	{
		OutputStream out = response.getOutputStream();
		out.write(Dson.toJsonString(result).getBytes(charset));
	}
	
	@Override
	public String renderType()
	{
		return DefaultResultType.Json;
	}
}
